﻿using System;
using static Utility.WinAPI;
using System.Windows;
using System.Diagnostics;

namespace WallpaperEngine.Core
{
    public class WallpaperProcess : WallpaperCore
    {
        private int Pid;

        private Hook hook;

        public WallpaperProcess(Wallpaper wallpaper) : base(wallpaper)
        {
            try
            {
                Process process = Process.Start(PathManager.Fullpath);
                process.WaitForInputIdle();
                DateTime startTime = DateTime.Now;
                while (process.MainWindowHandle == IntPtr.Zero)
                {
                    if ((DateTime.Now - startTime).Seconds > 3)
                    {
                        throw new Exception("无法找到此应用程序主窗口!");
                    }
                }
                SetParent(process.MainWindowHandle, _wallpaper.Handle);
                SetWindowLong(process.MainWindowHandle, WindowLongFlags.GWL_EXSTYLE, (int)WindowStylesEx.WS_EX_TOOLWINDOW);//WS_EX_TOOLWINDOW=128
                SetWindowLong(process.MainWindowHandle, WindowLongFlags.GWL_STYLE,
                    GetWindowLong(process.MainWindowHandle, WindowLongFlags.GWL_STYLE) & (~(int)WindowStyles.WS_CAPTION));//WS_CAPTION=12582912
                SetWindowPos(process.MainWindowHandle, IntPtr.Zero, 0, 0, _wallpaper.Fullscreen.Width, _wallpaper.Fullscreen.Height, SetWindowPosFlags.FrameChanged);
                ShowWindow(process.MainWindowHandle, CmdShow.SW_MAXIMIZE);//SW_MAXIMIZE=3
                if (Configuration.Config.AllowMouseHook)
                {
                    hook = new Hook(process.MainWindowHandle);
                }
                Pid = process.Id;
            }
            catch (Exception exception)
            {
                MessageBox.Show($"{exception.Data.ToString()}\n{exception.Message}\n{exception.Source}\n{exception.StackTrace}\n{exception.TargetSite}\n初始化应用程序壁纸失败!\n请将本窗口截图发给作者,谢谢");
            }
        }

        ~WallpaperProcess()
        { 
            if (Pid != 0)
            {
                if (hook != null)
                {
                    hook.Stop();
                }
                Process.GetProcessById(Pid).Kill();
                Debug.Print($"目标进程已终止,PID:{Pid}");
                Pid = 0;
            }
        }
    }
}
